package com.xbq.oauth.security;

import com.xbq.oauth.controller.ValidateCodeController;
import com.xbq.oauth.exceptions.ValidDateException;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * extends OncePerRequestFilter保证过滤器只执行一次
 * 自定义的SpringSecurity过滤器，用来过滤验证码信息
 */
public class ValidDateCodeFilter extends OncePerRequestFilter {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //只过滤登录请求
        if("/authentication/require".equals(request.getRequestURI()) ){
            //校验验证码

            try {
                validate(new ServletWebRequest(request));
            } catch (ServletRequestBindingException e) {
                return;
            }

        }

        //不是登录请求，那就直接调后面的过滤器
        filterChain.doFilter(request,response);
    }


    //校验验证码逻辑
    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        //step1：获取session中的验证码信息
        String validCode = (String) sessionStrategy.getAttribute(request,ValidateCodeController.SESSION_KEY);

        //step2：获取请求中的二维码信息
        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"valid_code");


        //step3：匹配验证码
        if(!validCode.equals(codeInRequest)){
            throw new ValidDateException("验证码不匹配！");
        }

        //step4：无论是否匹配成功，都移除掉之前的验证码信息
        sessionStrategy.removeAttribute(request,ValidateCodeController.SESSION_KEY);


    }
}
